package com.learn.spring_aop.dynamic_proxy.gglib_extends;

import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

public class GglibExtendsProxy {
    private static Enhancer enhancer = new Enhancer();
    
    /**
     * 产生目标类的代理对象
     *
     * @param target 目标类。被代理的对象
     * @return 代理类。代理目标类接口
     */
    public static Object createProxy(final Object target) {
        enhancer.setClassLoader(target.getClass().getClassLoader());
        enhancer.setSuperclass(target.getClass());
        enhancer.setCallback(new MethodInterceptor() {
            @Override
            public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
                System.out.println("方法前插入的操作");
                
                // 激活目标类内的目标方法
                Object result = method.invoke(target, objects);
                
                System.out.println("方法后插入的操作");
                return result;
            }
        });
        return enhancer.create();
    }
}
